package com.ruoyi.project.city.cityMasterList.service;

import java.math.BigDecimal;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.arronlong.httpclientutil.HttpClientUtil;
import com.arronlong.httpclientutil.common.HttpConfig;
import com.arronlong.httpclientutil.common.HttpHeader;
import com.arronlong.httpclientutil.exception.HttpProcessException;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.utils.CheckSignUtil;
import com.ruoyi.common.utils.MD5Util;
import com.ruoyi.common.utils.PropertiesFileUtil;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.module.packet.domain.Packet;
import com.ruoyi.project.user.appUser.domain.AppUser;
import com.ruoyi.project.user.appUser.service.IAppUserService;
import com.sun.net.httpserver.Authenticator;
import org.apache.http.Header;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.city.cityMasterList.mapper.CityMasterListMapper;
import com.ruoyi.project.city.cityMasterList.domain.CityMasterList;
import com.ruoyi.project.city.cityMasterList.service.ICityMasterListService;
import com.ruoyi.common.support.Convert;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 主城 服务层实现
 *
 * @author ruoyi
 * @date 2018-08-28
 */
@Service
public class CityMasterListServiceImpl implements ICityMasterListService {
    Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CityMasterListMapper cityMasterListMapper;
    @Autowired
    private IAppUserService appUserService;

    /**
     * 查询主城信息
     *
     * @param adCode 主城ID
     * @return 主城信息
     */
    @Override
    public CityMasterList selectCityMasterListById(Integer adCode) {
        return cityMasterListMapper.selectCityMasterListById(adCode);
    }

    /**
     * 查询主城列表
     *
     * @param cityMasterList 主城信息
     * @return 主城集合
     */
    @Override
    public List<CityMasterList> selectCityMasterListList(CityMasterList cityMasterList) {

        List<CityMasterList> newCityList = new ArrayList<CityMasterList>();

        List<CityMasterList> cityList = cityMasterListMapper.selectCityMasterListList(cityMasterList);

        for(int i=0; i< cityList.size(); i++){
            CityMasterList city = cityList.get(i);

            /**
             * 根据stage和leveltype判断城市是否开启
             * 涉及到之前的城市分裂，所以使用这个来判断
             */
            if(city.getStage() >= city.getLevelType()){
                city.setCityStatus("1");
            }else{
                city.setCityStatus("0");
            }
            newCityList.add(city);
        }

        return newCityList;
    }

    /**
     * 连表查询数据
     *
     * @param cityMasterList 主城信息
     * @return 主城集合
     */
    @Override
    public List<CityMasterList> selectCityMasterListListByJoin(CityMasterList cityMasterList) {

        //城市是否开启查询条件处理
        String cityStatus = cityMasterList.getCityStatus();
        if("1".equals(cityStatus)){
            cityMasterList.setCityOpen("yes");
        }else if ("0".equals(cityStatus)){
            cityMasterList.setCityNotOpen("yes");
        }

        List<CityMasterList> cityList = cityMasterListMapper.selectCityMasterListListByJoin(cityMasterList);
        for(int i=0; i< cityList.size(); i++){
            CityMasterList city = cityList.get(i);

            /**
             * 根据stage和leveltype判断城市是否开启
             * 涉及到之前的城市分裂，所以使用这个来判断
             */
            if(city.getStage() !=null && city.getStage() >= city.getLevelType()){
                city.setCityStatus("1");
            }else{
                city.setCityStatus("0");
            }
        }

        return cityList;
    }


    /**
     * 新增主城
     *
     * @param cityMasterList 主城信息
     * @return 结果
     */
    @Override
    public int insertCityMasterList(CityMasterList cityMasterList) {
        return cityMasterListMapper.insertCityMasterList(cityMasterList);
    }

    /**
     * 修改主城
     *
     * @param cityMasterList 主城信息
     * @return 结果
     */
    @Override
    public int updateCityMasterList(CityMasterList cityMasterList) {
        return cityMasterListMapper.updateCityMasterList(cityMasterList);
    }

    /**
     * 删除主城对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteCityMasterListByIds(String ids) {
        return cityMasterListMapper.deleteCityMasterListByIds(Convert.toStrArray(ids));
    }


    /**
     * 购买主城信息
     *
     * @param adCode    城市code
     * @param userPhone 用户手机号
     */
    @Override
    public AjaxResult buyCity(String adCode, String userPhone) {
        AppUser appUser = appUserService.selectAppUserByUserPhone(userPhone);
        if (appUser == null) {
            return AjaxResult.error("用户不存在");
        }

        AjaxResult result  = this.sendPostBuyCity(appUser, adCode);

        return result;

    }

    public AjaxResult sendPostBuyCity(AppUser appUser, String adCode) {

        //随机数
        String random = UUID.randomUUID().toString();
        String key = PropertiesFileUtil.getInstance("CheckSignKey").get("APP").toUpperCase();

        //构建请求参数
        JSONObject jsonO = new JSONObject();
        jsonO.put("userId", appUser.getAppUserId());
        log.info("userId====================="+appUser.getAppUserId());
        jsonO.put("cityCode", adCode);
        String jsonStr = jsonO.toJSONString();
        //签名map
        Map<String, String> signMap = new HashMap<String, String>();
        signMap.put("json", jsonStr);
        signMap.put("random", random);
        signMap.put("key", key);
        String sign = CheckSignUtil.formatUrlMap(signMap);

        //构建请求及连接
        String remoteServer_base_url = PropertiesFileUtil.getInstance("remoteServer").get("base_url");
        String url = remoteServer_base_url + "cityMaster/createCityTransactionRecordByBalance";
        String randomSign = MD5Util.MD5(random.concat("&").concat(key));
        Header[] headers = HttpHeader.custom()
                .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36")
                .other("random", random)
                .other("randomSign", randomSign)
                .build();


        //传输的参数
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("json", jsonStr);
        map.put("random", random);
        map.put("sign", sign);


        HttpConfig config = HttpConfig.custom()
                .headers(headers)    //设置headers，不需要时则无需设置
                .url(url)                    //设置请求的url
                .map(map)            //设置请求参数，没有则无需设置
                .encoding("utf-8") //设置请求和返回编码，默认就是Charset.defaultCharset()
                ;
        String reponse_result = null;
        try {
            reponse_result = HttpClientUtil.post(config);
        } catch (HttpProcessException e) {
            log.error("【平台购买主城】向服务器发送请求时出现异常");
            e.printStackTrace();
            return AjaxResult.error("向服务器发送请求时出现异常");
        }

        log.info("【平台购买主城】返回信息：{}", reponse_result);

        JSONObject resjsStr = null;
        try {
            resjsStr = JSONObject.parseObject(reponse_result);
        } catch (Exception e) {
            log.error("【平台购买主城】转换返回信息时出现异常");
            return AjaxResult.error("未能解析业务平台返回的信息");
        }
        String msg = resjsStr.getString("message");
        Integer code = Integer.parseInt(resjsStr.getString("code"));
        if (code == 0) {
            log.error("【平台购买主城】购买主城返回信息判定为失败");
            return AjaxResult.error(msg);
        } else if (code == 1) {
            log.info("【平台购买主城】购买主城返回信息判定为成功");
            return AjaxResult.success(msg);
        } else {
            log.info("【平台购买主城】未知的code类型：{}", code);
            return AjaxResult.error("未知的code类型：" + code);
        }
    }


    /**
     * 开放主城
     *
     * @param  ids 城市id
     * @return
     */
    public AjaxResult openCity(String ids){


        //随机数
        String random = UUID.randomUUID().toString();
        String key = PropertiesFileUtil.getInstance("CheckSignKey").get("APP").toUpperCase();

        Map<String, String> signMap = new HashMap<String, String>();
        signMap.put("adCodeList", ids);
        signMap.put("random", random);
        signMap.put("key", key);
        String sign = CheckSignUtil.formatUrlMap(signMap);

        //构建请求及连接
        String remoteServer_base_url = PropertiesFileUtil.getInstance("remoteServer").get("base_url");
        String url = remoteServer_base_url + "message/openCityByAdCode";
        String randomSign = MD5Util.MD5(random.concat("&").concat(key));
        Header[] headers = HttpHeader.custom()
                .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36")
                .other("random", random)
                .other("randomSign", randomSign)
                .build();


        //传输的参数
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("adCodeList", ids);
        map.put("random", random);
        map.put("sign", sign);


        HttpConfig config = HttpConfig.custom()
                .headers(headers)    //设置headers，不需要时则无需设置
                .url(url)                    //设置请求的url
                .map(map)            //设置请求参数，没有则无需设置
                .encoding("utf-8") //设置请求和返回编码，默认就是Charset.defaultCharset()
                ;
        String reponse_result = null;
        try {
            reponse_result = HttpClientUtil.post(config);
        } catch (HttpProcessException e) {
            log.error("【开放主城】向服务器发送请求时出现异常");
            e.printStackTrace();
            return AjaxResult.error("向服务器发送请求时出现异常");
        }

        log.info("【开放主城】返回信息：{}", reponse_result);

        JSONObject resjsStr = null;
        try {
            resjsStr = JSONObject.parseObject(reponse_result);
        } catch (Exception e) {
            log.error("【开放主城】转换返回信息时出现异常");
            return AjaxResult.error("未能解析业务平台返回的信息");
        }
        String msg = resjsStr.getString("message");
        Integer code = Integer.parseInt(resjsStr.getString("code"));
        if (code == 0) {
            log.error("【开放主城】购买主城返回信息判定为失败");
            return AjaxResult.error(msg);
        } else if (code == 1) {
            log.info("【开放主城】购买主城返回信息判定为成功");
            return AjaxResult.success(msg);
        } else {
            log.info("【开放主城】未知的code类型：{}", code);
            return AjaxResult.error("未知的code类型：" + code);
        }
    }

}
